import base64
import json
import KBEngine
import KBEDebug as log
import Functor
# from Crypto.Cipher import AES
from MailPoller import BasePoller, STATUS_CODES
import http_parser


appId = "wx110a0e6e097dec04"
appSecret = "587d3c5439dce08fd66e3b6accb9fc31"


# def decrypt(appId, sessionKey, encryptedData, iv):
#     # base64 decode
#     sessionKey = base64.b64decode(sessionKey)
#     encryptedData = base64.b64decode(encryptedData)
#     iv = base64.b64decode(iv)

#     cipher = AES.new(sessionKey, AES.MODE_CBC, iv)

#     decrypted = json.loads(_unpad(cipher.decrypt(encryptedData)))

#     if decrypted['watermark']['appid'] != appId:
#         raise Exception('Invalid Buffer')

#     return decrypted


# def _unpad(self, s):
#     return s[:-ord(s[len(s) - 1:])]


class WXReqAuthPoller(BasePoller):

    def processData(self, sock, fileno, datas):
        log.INFO_MSG(f'WXReqAuthPoller.processData datas: {datas}')
        try:
            data_src = datas.decode('utf-8')
            req = http_parser.http_parse(data_src)
            log.INFO_MSG(f'WXReqAuthPoller req: {req}')

            jdata = json.loads(req[2])
            log.INFO_MSG(f'WXReqAuthPoller.processData jdata: {jdata}')
            # """
            #     {
            #         'openId': 'oGZUI0egBJY1zhBYw2KhdUfwVJJE',
            #         'nickName': 'Band',
            #         'gender': 1,
            #         'language': 'zh_CN',
            #         'city': 'Guangzhou',
            #         'province': 'Guangdong',
            #         'country': 'CN',
            #         'avatarUrl': 'http://wx.qlogo.cn/mmopen/vi_32/aSKcBBPpibyKNicHNTMM0qJVh8Kjgiak2AHWr8MHM4WgMEm7GFhsf8OYrySdbvAMvTsw3mo8ibKicsnfN5pRjl1p8HQ/0',
            #         'unionId': 'ocMvos6NjeKLIBqg5Mr9QjxrP1FA',
            #         'watermark': {'timestamp': 1477314187, 'appid': 'wx4f4bc4dec97d474b'}
            #     }
            # """
            # info = decrypt(jdata['appId'], jdata['sessionKey'], jdata['encryptedData'], jdata['iv'])
            code = jdata['code']
            url = f'https://api.weixin.qq.com/sns/jscode2session?appid={appId}&secret={appSecret}&js_code={code}&grant_type=authorization_code'
            log.INFO_MSG(f'{url}')
            KBEngine.urlopen(url, Functor.Functor(self.onHttpCallback, sock, fileno))
            # self.closeRequest(sock, fileno, 200, req[2])
        except Exception as e:
            self.closeRequest(sock, fileno, 400, f'FAILURE: {e}')

    def onHttpCallback(self, sock, fileno, httpcode, data, headers, success, url):
        jdata = json.loads(data)
        log.INFO_MSG(f'onHttpCallback: {httpcode} {data} {success} {jdata}')
        self.closeRequest(sock, fileno, 200, data)

    def closeRequest(self, sock, fileno, code, msg):
        if fileno not in self._clients:
            print(f'RechargePoller already close {msg}')
            return

        response = 'HTTP/1.1 %d %s\r\n' % (code, STATUS_CODES.get(code, "UNKNOWN RESPONSE"))
        response += 'Content-Type: application/text\r\n'
        response += 'Content-Length: %d\r\n' % len(msg)
        response += '\r\n'
        response += msg

        sock.send(response.encode('utf-8'))
        KBEngine.deregisterReadFileDescriptor(sock.fileno())
        sock.close()
        del self._clients[fileno]
